<script setup lang="ts">
  import { ref, computed, watch } from 'vue';
  import Lodash from 'lodash';
  import TableLayout from '@/layout/table-layout.vue';
  import { usePageTable } from '@/hooks/arco/usePageTable';
  import { useForm } from '@/hooks/arco/useForm';
  import {
    queryInstDepartments,
    createInstDepartment,
    editInstDepartment,
    deleteInstDepartment,
  } from '@/api/structure-management/department';
  import { Modal, Message } from '@arco-design/web-vue';
  import DetailsDrawer from '@/components/details-drawer/index.vue';
  import {
    zipData,
    getDepartmentList,
    childrenDataList,
  } from '@/views/lhj-v1/util';

  const loading = ref(false);
  const baseNameMap = {
    itemID: { key: 'id', label: '部门ID' },
    itemName: { key: 'name', label: '部门名称', placeholder: '请输入部门名称' },
    itemParentID: { key: 'parentId', label: '上级部门', placeholder: '请选择上级部门' },
    itemParentName: { key: 'parentName', label: '上级部门' },
    itemNum: { key: 'staffCount', label: '部门人数' },
    createAt: { key: 'createTime', label: '创建时间' },
    btnAction: { label: '操作' },
    btnLook: { label: '查看' },
  };

  // 模态框默认配置
  const modalConfig = {
    title: '提示',
    bodyStyle: 'text-align: center;',
  };

  // 模态框
  const dataModal = ref({
    visible: false,
    type: '',
    title: '',
    cancelBtnText: '取消',
    okBtnText: '保存',
  });

  // 查询表格列配置
  const tableColumns = [
    {
      title: baseNameMap.itemID.label,
      dataIndex: baseNameMap.itemID.key,
      // ellipsis: true,
      // minWidth: 200,
    },
    {
      title: baseNameMap.itemName.label,
      dataIndex: baseNameMap.itemName.key,
      // minWidth: 140,
    },
    {
      title: baseNameMap.itemNum.label,
      dataIndex: baseNameMap.itemNum.key,
      // minWidth: 200,
    },
    {
      title: baseNameMap.createAt.label,
      dataIndex: baseNameMap.createAt.key,
      // minWidth: 300,
    },
    {
      title: baseNameMap.btnAction.label,
      align: 'center' as const,
      dataIndex: 'action',
      slotName: 'action',
      fixed: 'right',
      width: 100,
    },
  ];

  // 用作部门列表选择
  const dataDepartments = ref<any>({});
  // 从查询接口计算 [{label: string, value: string}] 格式部门列表
  const departmentsComputed = computed(() => {
    const departments: any[] = [{ label: '无', value: '无' }];
    const keys = Lodash.keys(dataDepartments.value);
    for (let i = 0; i < keys.length; i += 1) {
      const key = keys[i];
      const value = dataDepartments.value[key];
      departments.push({
        label: value,
        value: key,
      });
    }
    return departments;
  });

  const pageTable = usePageTable({
    searchForm: {
      state: {
        [baseNameMap.itemName.key]: '',
      },
    },
    table: {
      rowKey: baseNameMap.itemID.key,
      fakePage: true,
      apiFun: (query) => {
        return new Promise((resolve) => {
          queryInstDepartments(query[baseNameMap.itemName.key]).then((res) => {
            resolve(childrenDataList(res));
          });
        });
      },
      onSuccess(data) {
        dataDepartments.value = getDepartmentList(data);
      },
      columns: tableColumns,
    },
  });

  const modalForm = useForm({
    state: {
      [baseNameMap.itemID.key]: '',
      [baseNameMap.itemName.key]: '',
      [baseNameMap.itemParentID.key]: '',
    },
    rules: {
      [baseNameMap.itemID.key]: {
        required: false,
      },
      [baseNameMap.itemName.key]: {
        required: true,
        message: baseNameMap.itemName.placeholder,
      },
      [baseNameMap.itemParentID.key]: {
        required: true,
        message: baseNameMap.itemParentID.placeholder,
      },
    },
  });

  const drawerHandler = ref({
    props: {
      visible: false,
      raw: {} as any,
      data: {} as any,
      title: '部门详情',
      deleteText: '确定删除此部门吗？',
      deleteDesc: '提示：此部门下的员工需要被重新分配新的部门。',
      deleteApi: deleteInstDepartment,
    },
    showDrawer: (item: any) => {
      drawerHandler.value.props.visible = true;
      // console.log('item:', item)
      drawerHandler.value.props.raw = item;
      if (!item[baseNameMap.itemParentName.key]) {
        item[baseNameMap.itemParentName.key] = '无';
      }
      drawerHandler.value.props.data = zipData(item, [
        // baseNameMap.itemID,
        baseNameMap.itemParentName,
        baseNameMap.itemName,
        baseNameMap.itemNum,
        baseNameMap.createAt,
      ]);
    },
    onDelete: () => {
      pageTable.reload();
    },
    onEdit: (item: any) => {
      modalForm.state[baseNameMap.itemID.key] = item.id;
      modalForm.state[baseNameMap.itemName.key] = item.name;
      modalForm.state[baseNameMap.itemParentID.key] = item.parentId? item.parentId : '无';
      dataModal.value.type = 'edit';
    },
  });

  //
  const handleModalOk = () => {
    // console.log('modalForm:', modalForm.state);
    modalForm
      .validate()
      .then(() => {
        loading.value = true;
        // let modalContent = '确认新增部门？';
        let messageText = '新增成功！';
        let apiFunc: any = createInstDepartment;
        const jsonData: any = Lodash.cloneDeep(modalForm.state);
        if (dataModal.value.type === 'edit') {
          // modalContent = '确认保存部门信息？';
          messageText = '保存成功！';
          apiFunc = editInstDepartment;
        } else if (dataModal.value.type === 'add') {
          // jsonData.ll = '';
        } else {
          return;
        }
        if (jsonData.area && jsonData.area.length >= 3) {
          const [provinceCode, cityCode, districtCode] = jsonData.area;
          jsonData.provinceCode = provinceCode;
          jsonData.cityCode = cityCode;
          jsonData.districtCode = districtCode;
        }
        if (jsonData[baseNameMap.itemParentID.key] === '无' || !jsonData[baseNameMap.itemParentID.key]) {
          jsonData[baseNameMap.itemParentID.key] = '';
        }
        if (!apiFunc) return;
        apiFunc(jsonData)
          .then(() => {
            dataModal.value.type = '';
            Message.success(messageText);
            pageTable.reload();
          })
          .finally(() => {
            loading.value = false;
          });
      //   Modal.confirm({
      //     ...modalConfig,
      //     content: modalContent,
      //     onOk: (e) => {
            
      //     },
      //     onCancel(e) {
      //       loading.value = false;
      //     },
      //   });
      })
      .catch((err) => {
        console.error(err);
      });
  };

  watch(
    () => dataModal.value.type,
    (newVal) => {
      switch (newVal) {
        case 'add': {
          dataModal.value.title = '新增部门';
          modalForm.state[baseNameMap.itemName.key] = '';
          modalForm.state[baseNameMap.itemParentID.key] = '';
          break;
        }
        case 'edit': {
          dataModal.value.title = '编辑部门';
          break;
        }
        default:
          dataModal.value.visible = false;
          return;
      }
      dataModal.value.visible = true;
    }
  );
</script>

<template>
  <div class="m-department">
    <TableLayout v-bind="pageTable.bindProps" @create="dataModal.type = 'add'">
      <template #searchForm="{ state }">
        <a-form-item
          :field="baseNameMap.itemName.key"
          :label="baseNameMap.itemName.label"
        >
          <a-input
            v-model="state[baseNameMap.itemName.key]"
            :placeholder="'请输入' + baseNameMap.itemName.label"
            allow-clear
          />
        </a-form-item>
      </template>
      <template #action="{ record }">
        <a-space>
          <a-button
            size="small"
            type="text"
            @click="drawerHandler.showDrawer(record)"
            >{{ baseNameMap.btnLook.label }}</a-button
          >
        </a-space>
      </template>
    </TableLayout>
    <!-- 详情 drawer -->
    <DetailsDrawer
      v-bind="drawerHandler.props"
      @cancel="drawerHandler.props.visible = false"
      @delete="drawerHandler.onDelete"
      @edit="drawerHandler.onEdit"
    />
    <!-- 新增/编辑 Modal -->
    <div class="m-department-modal">
      <a-modal
        v-model:visible="dataModal.visible"
        top="20%"
        :align-center="false"
        @cancel="dataModal.type = ''"
      >
        <template #title>{{ dataModal.title }}</template>
        <a-form v-bind="modalForm.bindProps" layout="vertical">
          <a-form-item
            :field="baseNameMap.itemName.key"
            :label="baseNameMap.itemName.label"
            required
          >
            <a-input
              v-model="modalForm.state[baseNameMap.itemName.key]"
              :placeholder="'请输入' + baseNameMap.itemName.label"
            />
          </a-form-item>
          <a-form-item
            style="margin-bottom: 0"
            :field="baseNameMap.itemParentID.key"
            :label="baseNameMap.itemParentID.label"
            required
          >
            <a-select
              v-model="modalForm.state[baseNameMap.itemParentID.key]"
              :placeholder="'请选择该部门的' + baseNameMap.itemParentID.label"
            >
              <a-option
                v-for="(item, index) of departmentsComputed"
                :key="'dp-' + index"
                :value="item.value"
                :label="item.label"
              />
            </a-select>
          </a-form-item>
        </a-form>
        <template #footer>
          <ae-button purpose="cancel" @click="dataModal.type = ''">{{
            dataModal.cancelBtnText
          }}</ae-button>
          <ae-button purpose="save" :loading="loading" @click="handleModalOk">{{
            dataModal.okBtnText
          }}</ae-button>
        </template>
      </a-modal>
    </div>
  </div>
</template>

<style lang="less" scoped>
  .m-department {
  }
</style>
